const Router = require('koa-router')
const query = require('../util/db')
const user = new Router()

// 用户登录
// http://127.0.0.1:8080/user/login
user.post('/login',async ctx => {
    let userInfo = ctx.request.body
    let sql = `select * from huser where uemail = ? && upwd = ?`
    let result = await query(sql,[userInfo.email,userInfo.password])
    if(result.length === 0){
        ctx.body = {
            code: 201,
            msg: '用户名或密码错误'
        }
        return
    }
    const {uuid,unickname,uemail} = result[0]
    // 登录成功返回给客户端除密码以外的信息
    ctx.body = {
        code: 200,
        msg: '登录成功',
        data: {
            uuid,
            unickname,
            uemail
        }
    }
})

// 用户注册
// http://127.0.0.1:8080/user/reg
user.post('/reg',async ctx => {
    let regInfo = ctx.request.body
    const {email,password,nickname} = regInfo
    let sql1 = `select * from huser where uemail = ?`
    let result1 = await query(sql1,[email])
    if(result1.length === 0){
        let sql2 = `INSERT INTO huser (unickname,upwd,uemail )VALUES(?,?,?)`
        let result2 = await query(sql2,[nickname,password,email]);
        if(result2.affectedRows === 1){
            ctx.body = {
                code: 200,
                msg: '注册成功'
            }
        }else{
            ctx.body = {
                code: 202,
                msg: '注册失败'
            }
        }
    }else{
        ctx.body = {
            code : 201,
            msg: '该邮箱已被注册'
        }
    }
})

module.exports = user
